package com.example.jetpack.b_viewModel_livedata

import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.edit
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.ViewModelProvider
import com.example.jetpack.b_viewModel_livedata.livedata.BAActivity
import com.example.jetpack.databinding.ActivityBBinding
import com.example.material.util.launchActivity

class   BActivity : AppCompatActivity() {
    private lateinit var binding: ActivityBBinding
    private lateinit var sp: SharedPreferences

    private lateinit var viewModel: CounterViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        binding = ActivityBBinding.inflate(layoutInflater)
        val view = binding.root
        setContentView(view)
        ViewCompat.setOnApplyWindowInsetsListener(view) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        sp = getPreferences(MODE_PRIVATE)
        val countReversed = sp.getInt("counter_reversed", 0)

        /**
         *  ViewModel 基础用法
         */
        //viewModel = ViewModelProvider(this).get(FirstViewModel::class.java)

        /**
         *  ViewModel factory 基础用法
         */
        viewModel = ViewModelProvider(
            this,
            CounterViewModelFactory(countReversed)
        )[CounterViewModel::class.java]


        binding.plusOneBtn.setOnClickListener {
            viewModel.plusOne()
        }

        /**
         * LiveData 基础用法
         */
        viewModel.counter.observe(this) {
            binding.counter.text = "$it"
        }


        binding.livedataBtn.setOnClickListener {
            launchActivity<BAActivity>()
        }
    }

    override fun onPause() {
        super.onPause()
        sp.edit {
            putInt("counter_reversed", viewModel.counter.value ?: 0)
        }
    }
}